package com.example.mylibrary.utils

import android.content.Context
import android.content.SharedPreferences


object SpUtils {

    lateinit var packageName: String
    lateinit var context: Context
    private var sp: SharedPreferences? = null

    fun init(context: Context) {
        this.context = context
        packageName = context.packageName
    }

    fun put(key: String, any: Any?) {
        put(packageName, key, any)
    }

    fun get(key: String, default: Any): Any? {
        return get(packageName, key, default)
    }

    fun remove(key: String) {
        remove(packageName, key)
    }

    fun put(fileName: String, key: String, any: Any?) {
        if (sp == null) {
            sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        }
        val spEdit = sp?.edit()
        when (any) {
            is String -> spEdit?.putString(key, any)

            is Int -> spEdit?.putInt(key, any)

            is Boolean -> spEdit?.putBoolean(key, any)

            is Long -> spEdit?.putLong(key, any)

            is Float -> spEdit?.putFloat(key, any)

            is Set<*> -> spEdit?.putStringSet(key, any as MutableSet<String>?)
        }
        spEdit?.apply()
    }


    fun get(fileName: String, key: String, default: Any): Any? {
        if (sp == null) {
            sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        }
        return when (default) {
            is String -> sp?.getString(key, default)

            is Int -> sp?.getInt(key, default)

            is Boolean -> sp?.getBoolean(key, default)

            is Long -> sp?.getLong(key, default)

            is Float -> sp?.getFloat(key, default)

            is Set<*> -> sp?.getStringSet(key, default as Set<String>)

            else -> null
        }
    }

    fun remove(fileName: String, key: String) {
        if (sp == null) {
            sp = context.getSharedPreferences(fileName, Context.MODE_PRIVATE)
        }
        sp?.edit()?.remove(key)?.apply()
    }
}